package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.RefundUserDao;
import com.xbongbong.saas.domain.entity.RefundUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.subform.PaymentSheetTeamEnum;
import com.xbongbong.saas.enums.subform.RefundTeamEnum;
import com.xbongbong.saas.model.RefundUserModel;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author haibin.zhang
 * @version v1.0
 * @date 2019/4/11 15:12
 * @since v1.0
 */
@Component
@Service("refundUserModel")
public class RefundUserModelImpl implements RefundUserModel {
    @Resource
    private RefundUserDao refundUserDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;
    @Resource
    private EsHelper esHelper;


    @Override
    public Integer insert(RefundUserEntity entity) throws XbbException {
        Long now = DateTimeUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        Integer result = refundUserDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_REFUND_TEAM, entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_REFUND_TEAM);
        paasEsModel.insert(saveDTO);
//        paasEsModel.insert(entity, IndexTypeEnum.IDX_SAAS_REFUND_TEAM, entity.getCorpid(), entity.getId(), entity.getDataId());
        return result;
    }

    @Override
    public Integer update(RefundUserEntity entity) throws XbbException {
        Long now = DateTimeUtil.getInt();
        entity.setUpdateTime(now);
        Integer result = refundUserDao.update(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_REFUND_TEAM, entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_REFUND_TEAM);
        paasEsModel.update(saveDTO);
//        paasEsModel.update(entity, IndexTypeEnum.IDX_SAAS_REFUND_TEAM, entity.getCorpid(), entity.getId(), entity.getDataId());
        return result;
    }

    @Override
    public List<RefundUserEntity> findEntitys(Map<String, Object> param) {
        return refundUserDao.findEntitys(param);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return refundUserDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    @Override
    public Integer save(RefundUserEntity refundUserEntity) throws XbbException {
        if (refundUserEntity.getId() == null || refundUserEntity.getId().equals(0L)) {
            return insert(refundUserEntity);
        }
        return update(refundUserEntity);
    }

    @Override
    public void disbandedTeamByCustomerId(String corpid, List<Long> customerIdList) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termsQuery(RefundEnum.getEsAttr4Keyword(RefundEnum.CUSTOMER_ID),customerIdList));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
        List<PaasFormDataEntity> paasFormDataEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_REFUND,boolQueryBuilder,PaasFormDataEntity.class, Collections.singletonList(FieldTypeEnum.DATAID.getAlias()));
        if (paasFormDataEntityList.isEmpty()){
            return;
        }
        List<Long> dataIdIn = paasFormDataEntityList.stream().map(PaasFormDataEntity::getDataId).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid", corpid);
        map.put(ParameterConstant.DATA_ID_IN, dataIdIn);
        map.put("del", DelEnum.NORMAL.getDel());
        List<RefundUserEntity> refundUserEntityList = findEntitys(map);
        refundUserDao.deleteBatchByRefundIdIn(corpid,dataIdIn);
        for (RefundUserEntity entity : refundUserEntityList) {
            paasEsModel.delete(entity.getId(), corpid, IndexTypeEnum.IDX_SAAS_REFUND_TEAM, entity.getDataId());
        }
    }

    @Override
    public void delete(RefundUserEntity refundUserEntity) throws XbbException {
        refundUserEntity.setDel(1);
        refundUserEntity.setUpdateTime((long) DateUtil.getInt());
        refundUserDao.update(refundUserEntity);
        paasEsModel.delete(refundUserEntity.getId(), refundUserEntity.getCorpid(), IndexTypeEnum.IDX_SAAS_REFUND_TEAM, refundUserEntity.getDataId());
//        paasEsModel.update(refundUserEntity, IndexTypeEnum.IDX_SAAS_REFUND_TEAM, refundUserEntity.getCorpid(), refundUserEntity.getId(), refundUserEntity.getDataId());
    }

    @Override
    public List<UserTeamEntity> findBaseEntitys(Map<String, Object> map) {
        return refundUserDao.findBaseEntitys(map);
    }

    @Override
    public Integer deleteBatchByRefundIdIn(List<Long> refundIdIn, String corpid) throws XbbException {
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",DelEnum.NORMAL.getDel());
        map.put("refundIdIn",refundIdIn);
        List<RefundUserEntity> refundUserEntityList = findEntitys(map);
        for (RefundUserEntity entity : refundUserEntityList){
            paasEsModel.delete(entity.getId(), corpid, IndexTypeEnum.IDX_SAAS_REFUND_TEAM,entity.getDataId());
        }
        Integer result = refundUserDao.deleteBatchByRefundIdIn(corpid, refundIdIn);
        return result;
    }

    @Override
    public List<Long> getDataIdList(String corpid, Integer isMain, List<String> userId) {
        return refundUserDao.getDataIdList(corpid, isMain, userId);
    }

    @Override
    public void insertBatch(List<RefundUserEntity> refundUserEntityList, boolean isImport) throws XbbException {
        refundUserDao.insertBatch(refundUserEntityList);
        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserTeamToFormDataList(IndexTypeEnum.IDX_SAAS_REFUND_TEAM, refundUserEntityList);

        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_REFUND_TEAM));
        }

//        for (RefundUserEntity refundUserEntity : refundUserEntityList) {
//            InsertDTO insertDTO = new InsertDTO();
//            insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
//            insertDTO.setEsId(refundUserEntity.getCorpid() + "_" + refundUserEntity.getId());
//            insertDTO.setParent(refundUserEntity.getCorpid() + "_" + refundUserEntity.getDataId());
//            insertDTO.setSource(BeanUtil.convertBean2Map(refundUserEntity, false, true));
//            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_REFUND_TEAM);
//            insertDTOList.add(insertDTO);
//        }
        if (isImport) {
            paasEsModel.insertBatch(insertDTOList, WriteRequest.RefreshPolicy.NONE);
        } else {
            paasEsModel.insertBatch(insertDTOList);
        }
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del) throws XbbException {
        refundUserDao.batchUpdateByIdIn(corpid, dataIdIn, isMain, del);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_REFUND_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                map.put(RefundTeamEnum.getAttrConnectData(RefundTeamEnum.IS_MAIN), isMain);
            }
            if (Objects.nonNull(del)) {
                map.put(ParameterConstant.DEL, del);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_REFUND_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList);
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        refundUserDao.batchUpdateByIdIn(corpid, dataIdIn, isMain, del);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_REFUND_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                map.put(RefundTeamEnum.getAttrConnectData(RefundTeamEnum.IS_MAIN), isMain);
            }
            if (Objects.nonNull(del)) {
                map.put(ParameterConstant.DEL, del);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_REFUND_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy);
    }

    /**
     * 获取单个实体
     *
     * @param key    id主键
     * @param corpid 公司id
     * @return com.xbongbong.saas.domain.entity.RefundUserEntity
     * @author youli.chen
     * @date 2019/2/14 16:43
     */
    @Override
    public RefundUserEntity getByKey(Long key, String corpid) {
        return refundUserDao.getByKey(key, corpid);
    }

    @Override
    public void deleteBatchUser(List<RefundUserEntity> refundUserEntityList, String corpid, Integer del) throws XbbException {
        if (CollectionUtils.isEmpty(refundUserEntityList)) {
            return;
        }
        List<Long> idList = new ArrayList<>();
        List<InsertDTO> insertDTOList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.DEL, del);
        map.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
        for (RefundUserEntity entity : refundUserEntityList){
            idList.add(entity.getId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_REFUND_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_REFUND_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_REFUND_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_REFUND_TEAM.getType());
            insertDTO.setSource(map);
            insertDTOList.add(insertDTO);
        }
        deleteBatch(idList,corpid, del);
        paasEsModel.updateBatch(insertDTOList);
    }

    @Override
    public Map<Long, String> batchDeleteById(String corpid, List<Long> removeIdList) throws XbbException{
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid",corpid);
        map.put("del",0);
        map.put("idIn",removeIdList);
        List<RefundUserEntity> refundUserEntityList = findEntitys(map);
        refundUserDao.batchDeleteById(corpid,removeIdList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        Map<Long,String> refundUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (RefundUserEntity entity : refundUserEntityList){
            refundUserMap.put(entity.getDataId(),entity.getUserId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_REFUND_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_REFUND_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_REFUND_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_REFUND_TEAM.getType());
            Map<String,Object> sourceMap = new HashMap<>();
            sourceMap.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
            sourceMap.put(StringConstant.DEL,DelEnum.DELETE.getDel());
            insertDTO.setSource(sourceMap);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList);
        return refundUserMap;
    }

    @Override
    public List<RefundUserEntity> getByRefundId(String corpid, Long id) {
        return refundUserDao.getByRefundId(corpid, id);
    }

    @Override
    public void updateBatch(List<RefundUserEntity> refundUserEntityList, String corpid) throws XbbException {
        refundUserDao.updateBatch(refundUserEntityList, corpid);

        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserTeamToFormDataList(IndexTypeEnum.IDX_SAAS_REFUND_TEAM, refundUserEntityList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_REFUND_TEAM));
        }
        paasEsModel.updateBatch(insertDTOList);
    }

    private void deleteBatch(List<Long> idList, String corpid, Integer del) {
        refundUserDao.deleteBatch(idList, corpid, del);
    }


    /**
     *
     * @Description: 编辑团队成员标签
     * @param refundUserEntity
     * @return: void
     * @Author: shen.yang
     * @Date: 2022/1/17  14:20
     */
    @Override
    public void editLabel(RefundUserEntity refundUserEntity) throws XbbException {
        updateFormTeam(refundUserEntity);
    }

    /**
     * 更新协同人可编辑权限
     *
     * @param refundUserEntity
     */
    @Override
    public void updateEditFormPer(RefundUserEntity refundUserEntity) throws XbbException {
        updateFormTeam(refundUserEntity);
    }


    private void updateFormTeam(RefundUserEntity refundUserEntity) throws XbbException {
        Long updateTime = DateTimeUtil.getInt();
        refundUserEntity.setUpdateTime(updateTime);
        refundUserDao.update(refundUserEntity);
        InsertDTO insertDTO = new InsertDTO();
        String corpid = refundUserEntity.getCorpid();
        insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_REFUND_TEAM.getType() + "_" + corpid + "_" + refundUserEntity.getId());
        insertDTO.setParent(corpid + "_" + refundUserEntity.getDataId());
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("updateTime", updateTime);
        insertDTO.setSource(map);
        insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_REFUND_TEAM);
        paasEsModel.update(insertDTO);
    }

    /**
     * 批量更新团队的人员为协同人身份以及协同人的可编辑权限
     *
     * @param corpid
     * @param idIn
     * @param teamEntityList
     * @param isMain
     * @param needThrow
     * @throws XbbException
     */
    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow) throws XbbException {
        batchUpdateCoAndPerByUserIdIn(corpid, idIn, teamEntityList, isMain, needThrow, WriteRequest.RefreshPolicy.WAIT_UNTIL);
    }


    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer formPermission = teamEntityList.get(BasicConstant.ZERO).getFormPermission();
        refundUserDao.batchUpdateCoAndPerByUserIdIn(corpid, idIn, isMain, formPermission);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_REFUND_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(PaymentSheetTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_REFUND_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy, needThrow);
    }

}
